import Component from '@glimmer/component';
import { action } from '@ember/object';
import { tracked } from '@glimmer/tracking';
import { service } from '@ember/service';

export default class TeamProjectComponent extends Component {
  @service api;
  @service message;
  
  @tracked activeTab = 'gantt';
  @tracked isLoading = false;
  
  // Tab 配置
  tabs = [
    { id: 'gantt', name: '甘特图' },
    { id: 'requirements', name: '需求列表' },
    { id: 'participants', name: '需求参与人员' },
    { id: 'members', name: '人员列表' }
  ];

  // 数据状态
  @tracked requirements = [];
  @tracked allParticipants = []; // 存储所有参与人员数据
  @tracked filteredParticipants = []; // 存储筛选后的参与人员数据
  @tracked members = [];
  @tracked hiddenDates = [];
  @tracked participantFilters = {}; // 存储筛选条件

  constructor() {
    super(...arguments);
    this.loadData();
  }

  // 加载所有数据
  async loadData() {
    this.isLoading = true;
    try {
      await Promise.all([
        this.loadRequirements(),
        this.loadMembers(),
        this.loadParticipants(),
        this.loadHiddenDates()
      ]);
    } catch (error) {
      console.error('加载数据失败:', error);
    } finally {
      this.isLoading = false;
    }
  }

  // 加载需求数据
  async loadRequirements() {
    const data = await this.api.getRequirements();
    this.requirements = this.api.transformRequirementsData(data);
  }

  // 加载成员数据
  async loadMembers() {
    const data = await this.api.getMembers();
    this.members = this.api.transformMembersData(data);
  }

  // 加载参与人员数据
  async loadParticipants(params = {}) {
    // 如果传入了筛选参数，则更新筛选条件并应用筛选
    if (Object.keys(params).length > 0) {
      this.participantFilters = params;
      this.applyParticipantFilters();
    } else {
      // 如果没有筛选参数，重新加载所有数据
      const data = await this.api.getRequirementParticipants();
      // 使用API转换方法确保数据格式一致
      this.allParticipants = this.api.transformParticipantsData(data);
      this.filteredParticipants = [...this.allParticipants];
      this.participantFilters = {};
      
      console.log('父组件加载参与人员数据完成:', {
        allParticipants: this.allParticipants.length,
        filteredParticipants: this.filteredParticipants.length,
        sampleData: this.allParticipants.slice(0, 3) // 显示前3条数据作为样本
      });
    }
  }

  // 应用参与人员筛选条件
  applyParticipantFilters() {
    if (this.allParticipants.length === 0) return;
    
    let filtered = [...this.allParticipants];
    
    // 按需求ID筛选
    if (this.participantFilters.requirementId) {
      filtered = filtered.filter(p =>
        p.requirementId?.toString() === this.participantFilters.requirementId
      );
    }
    
    // 按人员ID筛选
    if (this.participantFilters.memberId) {
      filtered = filtered.filter(p =>
        p.memberId?.toString() === this.participantFilters.memberId
      );
    }
    
    // 按类型筛选
    if (this.participantFilters.type) {
      filtered = filtered.filter(p =>
        p.type === this.participantFilters.type
      );
    }
    
    // 按人员姓名筛选
    if (this.participantFilters.memberName) {
      filtered = filtered.filter(p =>
        p.memberName?.toLowerCase().includes(this.participantFilters.memberName.toLowerCase())
      );
    }
    
    // 按时间范围筛选
    if (this.participantFilters.queryStartTime || this.participantFilters.queryEndTime) {
      filtered = filtered.filter(p => {
        const startTime = p.startTime ? new Date(p.startTime) : null;
        const endTime = p.endTime ? new Date(p.endTime) : null;
        
        let match = true;
        
        if (this.participantFilters.queryStartTime && startTime) {
          const filterStartTime = new Date(this.participantFilters.queryStartTime);
          match = match && startTime >= filterStartTime;
        }
        
        if (this.participantFilters.queryEndTime && endTime) {
          const filterEndTime = new Date(this.participantFilters.queryEndTime);
          match = match && endTime <= filterEndTime;
        }
        
        return match;
      });
    }
    
    this.filteredParticipants = filtered;
  }

  // 加载隐藏日期数据
  async loadHiddenDates() {
    const data = await this.api.getHiddenDates();
    this.hiddenDates = this.api.transformHiddenDatesData(data);
  }

  @action
  switchTab(tabId) {
    this.activeTab = tabId;
  }

  @action
  async updateRequirement(requirementId, updates) {
    try {
      const updatedRequirement = await this.api.updateRequirement(requirementId, updates);
      if (updatedRequirement) {
        // 重新加载需求列表，确保数据是最新的
        await this.loadRequirements();
      }
    } catch (error) {
      console.error('更新需求失败:', error);
    }
  }

  @action
  async addRequirement(requirement) {
    try {
      const newRequirement = await this.api.addRequirement(requirement);
      if (newRequirement) {
        // 重新加载需求列表，确保数据是最新的
        await this.loadRequirements();
      }
    } catch (error) {
      console.error('新增需求失败:', error);
    }
  }

  @action
  async deleteRequirement(requirementId) {
    try {
      await this.api.deleteRequirement(requirementId);
      // 重新加载需求列表和参与人员列表，确保数据是最新的
      await Promise.all([
        this.loadRequirements(),
        this.loadParticipants()
      ]);
    } catch (error) {
      console.error('删除需求失败:', error);
    }
  }

  @action
  async updateParticipant(participantId, updates) {
    try {
      // 清除缓存，确保获取最新数据
      this.api.clearParticipantsCache();
      const updatedParticipant = await this.api.updateRequirementParticipant(participantId, updates);
      if (updatedParticipant) {
        // 重新加载参与人员列表，确保数据是最新的
        await this.loadParticipants();
      }
    } catch (error) {
      console.error('更新参与人员失败:', error);
    }
  }

  @action
  async addParticipant(participant) {
    try {
      // 清除缓存，确保获取最新数据
      this.api.clearParticipantsCache();
      const newParticipant = await this.api.addRequirementParticipant(participant);
      if (newParticipant) {
        // 重新加载参与人员列表，确保数据是最新的
        await this.loadParticipants();
      }
    } catch (error) {
      console.error('新增参与人员失败:', error);
    }
  }

  @action
  async deleteParticipant(participantId) {
    try {
      // 清除缓存，确保获取最新数据
      this.api.clearParticipantsCache();
      await this.api.deleteRequirementParticipant(participantId);
      // 重新加载参与人员列表，确保数据是最新的
      await this.loadParticipants();
    } catch (error) {
      console.error('删除参与人员失败:', error);
    }
  }

  @action
  async updateMember(memberId, updates) {
    try {
      const updatedMember = await this.api.updateMember(memberId, updates);
      if (updatedMember) {
        // 重新加载成员列表，确保数据是最新的
        await this.loadMembers();
      }
    } catch (error) {
      console.error('更新成员失败:', error);
    }
  }

  @action
  async addMember(member) {
    try {
      const newMember = await this.api.addMember(member);
      if (newMember) {
        // 重新加载成员列表，确保数据是最新的
        await this.loadMembers();
      }
    } catch (error) {
      console.error('新增成员失败:', error);
    }
  }

  @action
  async deleteMember(memberId) {
    try {
      await this.api.deleteMember(memberId);
      // 重新加载成员列表和参与人员列表，确保数据是最新的
      await Promise.all([
        this.loadMembers(),
        this.loadParticipants()
      ]);
    } catch (error) {
      console.error('删除成员失败:', error);
    }
  }

  // 计算需求的总开发工时和测试工时
  getRequirementHours(requirementId) {
    const requirementParticipants = this.allParticipants.filter(p => p.requirementId === requirementId);
    let devHours = 0;
    let testHours = 0;

    requirementParticipants.forEach(participant => {
      const member = this.members.find(m => m.id === participant.memberId);
      if (member) {
        // 使用手动输入的工作量，转换为小时（假设1人天=8小时）
        const hours = (participant.workload || 0) * 8;

        if (member.type === '前端' || member.type === '后端') {
          devHours += hours;
        } else if (member.type === '测试') {
          testHours += hours;
        }
      }
    });

    return { devHours, testHours };
  }

  // 刷新数据
  @action
  async refreshData(params) {
    if (params) {
      // 如果有筛选参数，只重新加载参与人员数据
      await this.loadParticipants(params);
    } else {
      // 如果没有筛选参数，重新加载所有数据
      await this.loadData();
    }
  }

  // 退出登录
  @action
  logout() {
    this.api.logout();
    this.message.success('已退出登录');
  }
}